package com.starp.add.service;

import com.starp.add.repository.MyRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.Iterator;

@Service
public class RepositoryImpl implements MyRepository {

    private static final int BATCH_SIZE = 5000 ;

    private final javax.persistence.EntityManager em;

//    public ExamineResultsRepositoryImpl(javax.persistence.EntityManager em) {
//        this.em = em;
//    }

    public RepositoryImpl(EntityManager em) {
        this.em = em;
    }


    @Override
    @Transactional
    public <S extends T,T> Iterable<S> batchSave(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()){
            em.persist(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0){
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0){
            em.flush();
            em.clear();
        }
        return var1;
    }

    @Override
    public <S extends T,T> Iterable<S> batchUpdate(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()){
            em.merge(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0){
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0){
            em.flush();
            em.clear();
        }
        return var1;
    }

//    @Override
//    @Transactional
//    public <S extends T, T> Iterable<S> batchSave(Iterable<S> var1) {
//        return null;
//    }
//
//    @Override
//    public <S extends T, T> Iterable<S> batchUpdate(Iterable<S> var1) {
//        return null;
//    }
}
